package com.xxl.job.executor.service.jobhandler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.bizsys.domain.AppUserMark;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.market.config.MarketUserConfig;
import com.ruoyi.market.service.IMarketUserService;
import com.ruoyi.market.util.HttpConnetUtil;
import com.ruoyi.market.vo.MarketUserLabelVo;
import com.ruoyi.system.service.ISysDictDataService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 营销用户标签取数任务
 *
 * @author pgc
 * @date: 2022-02-25
 */
@Slf4j
@Component
public class MarketUserLabelJob {

    @Autowired
    IMarketUserService marketUserService;

    @Autowired
    MarketUserConfig marketUserConfig;

    /**
     * 电销取数标签配置
     */
    public static String MARKET_USER_LABEL_CONFIG = "market_user_label_config";

    /**
     * 电销取数标签配置状态
     */
    public static String status = "0";

    @Autowired
    ISysDictDataService sysDictDataService;

    /**
     * 根据标签及时间取数
     *
     * @jobParam userLabel beginDate endDate
     * 示例：a-b-c,2022-08-01,2022-08-05
     */
    @XxlJob("pushUserLabelJobHandler")
    public void execute() {
        XxlJobHelper.log("用户标签电销取数 Start >>>>>>>>>>");

        List<MarketUserLabelVo> marketUserLabelVos = new ArrayList<>();

        String jobParam = XxlJobHelper.getJobParam();
        if (StringUtils.isNotBlank(jobParam)) {
            String[] paramArray = jobParam.split(",");
            if (paramArray.length < 3) {
                XxlJobHelper.handleFail("用户标签电销取数执行参数不足");
                XxlJobHelper.log("用户标签电销取数 End >>>>>>>>>>");
                return;
            }

            String userLabel = paramArray[0];
            String beginDate = paramArray[1];
            String endDate = paramArray[2];

            if (!userLabel.isEmpty() && !beginDate.isEmpty() && !endDate.isEmpty()) {
                String[] userLabels = userLabel.split("-");
                for (int i = 0; i < userLabels.length; i++) {
                    MarketUserLabelVo marketUserLabelVo = new MarketUserLabelVo();
                    marketUserLabelVo.setUserLabel(userLabels[i]);
                    marketUserLabelVo.setBeginDate(beginDate);
                    marketUserLabelVo.setEndDate(endDate);
                    marketUserLabelVos.add(marketUserLabelVo);
                }
            }
        // 读取用户标签取数配置
        } else {
            SysDictData params = new SysDictData();
            params.setDictType(MARKET_USER_LABEL_CONFIG);
            params.setStatus(status);
            List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(params);
            for (int i = 0; i < sysDictDataList.size(); i++) {
                SysDictData sysDictData = sysDictDataList.get(i);
                MarketUserLabelVo marketUserLabelVo = new MarketUserLabelVo();
                marketUserLabelVo.setUserLabel(sysDictData.getDictLabel());
                marketUserLabelVo.setIntervalHours(Integer.valueOf(sysDictData.getDictValue()));
                marketUserLabelVos.add(marketUserLabelVo);
            }
        }

        List<AppUserMark> appUserMarkList = marketUserService.selectAppUserMarkList(marketUserLabelVos);
        JSONObject jsonParam = marketUserFormatt(appUserMarkList, "add");
        if (jsonParam.getJSONArray("data").size() <= 0) {
            XxlJobHelper.log("用户标签电销取数：0 数据");
            XxlJobHelper.log("用户标签电销取数 End >>>>>>>>>>");
            return;
        }

        // 推送至营销系统
        String resultInfo = null;
        try {
            resultInfo = HttpConnetUtil.sendPost(marketUserConfig.getMarketUserImportUrl(), jsonParam.toJSONString());
            XxlJobHelper.log("营销用户推送至 营销系统： " + resultInfo);
        } catch (Exception e) {
            log.error("推送至营销系统 异常");
            XxlJobHelper.log(e);
            XxlJobHelper.handleFail("推送至营销系统 异常");
        }

        XxlJobHelper.log("用户标签电销取数 End >>>>>>>>>>");
    }

    /**
     * 更新用户标签
     */
    @XxlJob("updateUserLabelJobHandler")
    public void updateUserLabelJobHandler() {
        XxlJobHelper.log("更新用户标签 Start >>>>>>>>>>");

        String intervalTime = XxlJobHelper.getJobParam();
        if (StringUtils.isBlank(intervalTime)) {
            XxlJobHelper.handleFail("更新用户标签需要输入参数");
            XxlJobHelper.log("更新用户标签 End >>>>>>>>>>");
            return;
        }

        List<AppUserMark> appUserMarkList = marketUserService.selectAppUserMarkListByTime(Integer.valueOf(intervalTime));
        JSONObject jsonParam = marketUserFormatt(appUserMarkList, "update");
        if (jsonParam.getJSONArray("data").size() <= 0) {
            XxlJobHelper.log("更新用户标签 End >>>>>>>>>> 无待处理数据");
            return;
        }

        // 推送至营销系统
        String resultInfo = null;
        try {
            resultInfo = HttpConnetUtil.sendPost(marketUserConfig.getMarketUserImportUrl(), jsonParam.toJSONString());
            XxlJobHelper.log("营销用户推送至 营销系统： " + resultInfo);
        } catch (Exception e) {
            log.error("推送至营销系统 异常");
            XxlJobHelper.log(e);
            XxlJobHelper.handleFail("推送至营销系统 异常");
        }

        XxlJobHelper.log("更新用户标签 End >>>>>>>>>>");
    }

    /**
     * 推送营销系统用户数据拼接
     *
     * @param appUserMarkList
     * @return
     */
    public JSONObject marketUserFormatt(List<AppUserMark> appUserMarkList, String type) {
        JSONObject jsonParam = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        for (AppUserMark marketUser : appUserMarkList) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userName", marketUser.getLastName());
            jsonObject.put("callPhone", marketUser.getRegisterPhone());
            jsonObject.put("bvnPhone", marketUser.getBvnPhone());
            jsonObject.put("userId", marketUser.getUserId());
            jsonObject.put("quota", marketUser.getCreditLine());
            jsonObject.put("custNo", marketUser.getCustNo());
            jsonObject.put("usedLimit", marketUser.getLoanQuota());
            jsonObject.put("firstTag", marketUser.getFirstTag());
            jsonObject.put("secondTag", marketUser.getSecondTag());
            jsonObject.put("gender", marketUser.getGender());
            jsonObject.put("birthday", marketUser.getBirthday());

            // 本次提额额度
            jsonObject.put("increasedLimit", marketUser.getIncreasedAmt());
            jsonObject.put("increasedCreateTime", marketUser.getIncreasedCreateTime());
            jsonObject.put("remark", marketUser.getRemark());

            // 增加版本号，用户等级
            jsonObject.put("appVersion", marketUser.getAppVersion());
            jsonObject.put("creditRating", marketUser.getCreditRating());

            jsonArray.add(jsonObject);
        }
        jsonParam.put("requestType", type);
        jsonParam.put("data", jsonArray);
        return jsonParam;
    }
}
